package com.piece.core.framework.util.basic;

import com.piece.core.framework.enums.LocalType;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import java.util.Locale;

/**
 * 获取i18n资源文件
 */
public class I18nUtil {

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     */
    public static String message(String code, Object... args) {
        try {
            MessageSource messageSource = SpringUtil.getBean(MessageSource.class);
            Locale locale = LocaleContextHolder.getLocale();
            String msg = messageSource.getMessage(code, args, locale);
            return msg == null ? code : msg;
        } catch (Exception e) {
            return code;
        }
    }

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param messageSource
     * @param code 消息键
     * @param args 参数
     */
    public static String message(MessageSource messageSource, String code, Object... args) {
        try {
            Locale locale = LocaleContextHolder.getLocale();
            String msg = messageSource.getMessage(code, args, locale);
            return msg == null ? code : msg;
        } catch (Exception e) {
            return code;
        }
    }

    public static void changeLocal(LocalType local) {
        switch (local) {
            case EN:
                LocaleContextHolder.setLocale(Locale.ENGLISH);
                break;
            case CN:
            default:
                LocaleContextHolder.setLocale(Locale.CHINA);
        }
    }
}
